﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using mesoBoard.Web.Core;
using System.IO;
using mesoBoard.Web;
using mesoBoard.Services;
using System.Reflection;
using Ninject.Web.Mvc;
using Ninject;
using Ninject.Modules;
using mesoBoard.Data;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using mesoBoard.Common;
using System.Web.Configuration;
using System.Configuration;

namespace mesoBoard.Web
{
    public class MvcApplication : NinjectHttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            AreaRegistration.RegisterAllAreas();

            string[] pluginFiles = Directory.GetFiles(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plugins"), "*.dll");

            foreach (string plugin in pluginFiles)
            {
                Assembly loadPlugin = Assembly.LoadFrom(plugin);

                Type toLoad = loadPlugin.GetType(loadPlugin.GetName().Name + ".PluginDetails");

                IPluginDetails pluginDetails = Activator.CreateInstance(toLoad) as IPluginDetails;

                foreach (var f in pluginDetails.Routes)
                    routes.Add(f);
            }

            routes.MapRoute(
                "Installer",
                "Installer",
                new { controller = "Install", action = "Index"}
            );

            routes.MapRoute(
                "Default",                                              // Route name
                "{controller}/{action}/{id}",                           // URL with parameters
                new { controller = "Board", action = "Index", id = UrlParameter.Optional }  // Parameter defaults
            );
        }
         
        protected override void OnApplicationStarted()
        {
            if (bool.Parse(System.Configuration.ConfigurationManager.AppSettings["Installed"]))
                SiteConfig.UpdateCache();

            RegisterRoutes(RouteTable.Routes);
            System.Web.Mvc.ViewEngines.Engines.Clear();
            System.Web.Mvc.ViewEngines.Engines.Add(new mesoBoardViewEngine());
            RegisterAllControllersIn(Assembly.GetExecutingAssembly());

        }

        protected override IKernel CreateKernel()
        {
            var modules = new INinjectModule[]
                {
                    new WebModule()
                };

            return new StandardKernel(modules);
        }
    }
}